package com.pikaqiu.service.impl;

import com.google.common.cache.LoadingCache;
import com.pikaqiu.common.Const;
import com.pikaqiu.common.ServerResponse;
import com.pikaqiu.common.TokenCache;
import com.pikaqiu.dao.UserMapper;
import com.pikaqiu.pojo.User;
import com.pikaqiu.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

/**
 * Created by Administrator on 2018/6/4.
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 登录接口
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    public ServerResponse<User> login(String userName, String password) {

        User user = userMapper.selectByUserName(userName);

        String MD5PassWord = DigestUtils.md5DigestAsHex(password.getBytes());

        if (user == null || !user.getPassword().equals(MD5PassWord)) {

            return ServerResponse.createByErrorMessage("用户名或密码错误");

        }

        user.setPassword(null);

        user.setQuestion(null);

        user.setAnswer(null);

        return ServerResponse.createBySuccess(user, "登录成功");

    }

    /**
     * 注册接口
     *
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> register(User user) {

        User existUser = userMapper.selectByUserName(user.getUsername());

        if (existUser != null) {

            return ServerResponse.createByErrorMessage("用户名已经存在");
        }
        User emailUser = userMapper.selectByEmail(user.getEmail());

        if (emailUser != null) {

            return ServerResponse.createByErrorMessage("邮箱已经存在");
        }

        //设置普通用户权限
        user.setRole(Const.Role.ROLE_CUSTOMER);

        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        int insert = userMapper.insert(user);

        if (insert == 1) {
            return ServerResponse.createBySuccessMessage("注册成功");
        }

        return ServerResponse.createByErrorMessage("新增失敗");
    }

    @Override
    public ServerResponse<String> checkEmail(String email) {
        User user = userMapper.selectByEmail(email);
        if (user == null) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    @Override
    public ServerResponse<String> checkUserName(String userName) {
        User user = userMapper.selectByUserName(userName);
        if (user == null) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    @Override
    public ServerResponse<String> checkVaild(String str, String type) {

        User user = null;

        switch (type) {
            case "userName": {
                user = userMapper.selectByUserName(str);
                break;
            }
            case "email": {
                user = userMapper.selectByEmail(str);
                break;
            }
        }

        if (user == null) {
            return ServerResponse.createBySuccess();
        }

        return ServerResponse.createByError();
    }

    @Override
    public ServerResponse selectQuestion(String userName) {

        User user = userMapper.selectByUserName(userName);

        if (user == null) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        user.setPassword(null);


        return ServerResponse.createBySuccess(user);
    }

    @Override
    public ServerResponse checkAnswer(String userName, String question, String answer) {

        int resultCount = userMapper.checkAnswer(userName, question, answer);

        if (resultCount > 0) {

            String token = UUID.randomUUID().toString();

            TokenCache.setKey(TokenCache.TOKEN_PREFIX + userName, token);

            return ServerResponse.createBySuccess(token);
        }

        return ServerResponse.createByErrorMessage("问题答案错误");
    }

    @Override
    public ServerResponse forgetRestPassword(String userName, String newPassword, String token) {
        if (StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("需要传递token");
        }

        User user = userMapper.selectByUserName(userName);

        if (user == null) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        String cacheToken = TokenCache.getKey(TokenCache.TOKEN_PREFIX + userName);

        if (StringUtils.equals(token, cacheToken)) {

            String MD5password = DigestUtils.md5DigestAsHex(newPassword.getBytes());

            user.setPassword(MD5password);

            int count = userMapper.updatePasswordByUserName(userName, MD5password);

            if (count > 0) {
                return ServerResponse.createBySuccessMessage("修改成功");
            }
        }
        return ServerResponse.createByErrorMessage("修改失败");
    }

    @Override
    public ServerResponse restPassword(String passwordOld, String passwordNew, User user) {

        User selectByUserName = userMapper.selectByUserName(user.getUsername());

        if (!selectByUserName.getPassword().equals(DigestUtils.md5DigestAsHex(passwordOld.getBytes()))) {
            return ServerResponse.createByErrorMessage("密码错误");
        }

        user.setPassword(DigestUtils.md5DigestAsHex(passwordNew.getBytes()));

        int count = userMapper.updateByPrimaryKeySelective(user);

        if (count > 0) {
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }

        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    @Override
    public ServerResponse<User> updateUserInfo(User user) {

        //count > 0
        int count = userMapper.checkEmailByUserId(user.getEmail(), user.getId());

        if (count > 0) {
            return ServerResponse.createByErrorMessage("email已经存在");
        }

        User updateUser = new User();

        updateUser.setQuestion(user.getQuestion());

        updateUser.setId(user.getId());

        updateUser.setPhone(user.getPhone());

        updateUser.setAnswer(user.getAnswer());

        updateUser.setEmail(user.getEmail());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);

        if (updateCount > 0) {
            return ServerResponse.createBySuccess(user, "修改成功");
        }

        return ServerResponse.createByErrorMessage("更新失败");
    }

    @Override
    public ServerResponse getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);

        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(null);

        return ServerResponse.createBySuccess(user);
    }

    @Override
    public boolean checkUserRole(User user) {
        if (user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN) {
            return true;
        }
        return false;
    }
}
